package my

import akka.actor.{Actor, ActorLogging, ActorRef, ReceiveTimeout}
import my.MyWorker.{Task, Work}

import scala.concurrent.duration._

/**
  * Created by shichen on 2017/8/3.
  */
object MyWorker {
  case class Work(name: String,master: ActorRef)
  case object WorkDepleted
  case class Task(input: List[String],master: ActorRef)
}

class MyWorker extends Actor with ActorLogging {
  import MyMaster._
  import context._
  def receive = idle

  def idle: Receive = {
    case Work(name,master) =>
      //这个为什么要放在第一行来写？
      context.become(enlisted(name,master))
      //这里是将一个Job拆分成多个Work
      log.info("recv work from router,start request work for job {}",name)

      //为什么不用sender，非得要把sender作参数传过来
      master ! Enlist(self)
      master ! NextTask
      watch(master)
      setReceiveTimeout(30 seconds)
  }

  def enlisted(name: String,master: ActorRef):Receive = {
    case ReceiveTimeout =>
      //怎么知道是Enlist timeout还是NextWork timeout ??
      //不过超时重试应该就是为请求任务而作的，Enlist如果没有成功怎么办？
      log.info("recv time out, requesting work again")
      master ! NextTask
    case Task(textPart,master) =>
      log.info("recv task from master, stop requesting work")
  }
}
